﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.IO;
using System.Windows.Media.Imaging;
using System.Globalization;
using System.Windows.Media;
using System.Windows.Controls;

namespace DB_Test
{
	public class ByteArrayToImageConverter : IValueConverter
	{
		#region IValueConverter Members
		/// <summary>
		/// Converts a value.
		/// </summary>
		/// <param name="value">The value produced by the binding source.</param>
		/// <param name="targetType">The type of the binding target property.</param>
		/// <param name="parameter">The converter parameter to use.</param>
		/// <param name="culture">The culture to use in the converter.</param>
		/// <returns>
		/// A converted value. If the method returns null, the valid null value is used.
		/// </returns>
		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
            if (value == null)
                return null;

			byte[] array = (byte[])value;

			string tempFile = Path.GetTempFileName();
			File.WriteAllBytes(tempFile, array);
			BitmapImage image = new BitmapImage();
			image.BeginInit();
			image.CacheOption = BitmapCacheOption.OnLoad;
			image.UriSource = new Uri(tempFile);
			image.EndInit();
			File.Delete(tempFile);

			return image;
		}
		/// <summary>
		/// Nothing does.
		/// </summary>
		/// <param name="value">The value that is produced by the binding target.</param>
		/// <param name="targetType">The type to convert to.</param>
		/// <param name="parameter">The converter parameter to use.</param>
		/// <param name="culture">The culture to use in the converter.</param>
		/// <returns>
		/// A converted value. If the method returns null, the valid null value is used.
		/// </returns>
		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
		{
            if (value == null)
                return null;

            BitmapSource image = (BitmapSource)value;
            MemoryStream stream = new MemoryStream();
            
            BitmapEncoder encoder = new JpegBitmapEncoder();            
            encoder.Frames.Add(BitmapFrame.Create(image));
            encoder.Save(stream);

            stream.Seek(0, SeekOrigin.Begin);

            byte[] result = new byte[stream.Length];
            BinaryReader br = new BinaryReader(stream);
            br.Read(result, 0, (int)stream.Length);

            br.Close();
            stream.Close();

            return result;
		}
		#endregion
	}
}
